﻿using ConfigInfoWebPlatform.API.BusinessCommon;
using ConfigInfoWebPlatform.API.DBCommon;
using ConfigInfoWebPlatform.API.ViewModel;
using ConfigInfoWebPlatform.Model;
using ConfigInfoWebPlatform.Nlog;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ConfigInfoWebPlatform.API.Controllers
{
    /// <summary>
    /// 组织控制器
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class OrganizationController : ControllerBase
    {
        readonly LogHelper _log;
        readonly string configRootPath;
        readonly string initDB;

        /// <summary>
        /// 组织控制器
        /// </summary>
        public OrganizationController(LogHelper logHelper, IConfiguration configuration)
        {
            _log = logHelper;
            configRootPath = configuration["AppSetting:configPath"].ToString();
            initDB = configuration["AppSetting:initDB"].ToString();
        }

        /// <summary>
        /// 分页获取组织列表数据
        /// </summary>
        [HttpGet("index")]
        public IActionResult Index(int page, int limit)
        {
            //获取当前登录用户信息
            UserInfoModel identity = new UserInfoModel();
            var userJsonStr = Base64Helper.DeCodeBase64(65001, Request.Headers["user"]);
            identity = Newtonsoft.Json.JsonConvert.DeserializeObject<UserInfoModel>(userJsonStr);

            List<OrganizationListModel> list = new List<OrganizationListModel>();
            List<OrganizationListModel> pageList = new List<OrganizationListModel>();
            DAL_Organization organizationDal = new DAL_Organization();
            //获取所有组织数据
            list = organizationDal.GetOrganizationList(identity?.D_id, identity?.Name == "admin" ? true : false);
            int totalcount = 0;
            if (list.Any())
            {
                totalcount = list.Count;
                pageList = list.Skip((page - 1) * limit).Take(limit).ToList();
            }
            return new JsonResult(new { code = 0, msg = "success", count = totalcount, data = pageList });
        }

        /// <summary>
        /// 保存组织信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("saveorganization")]
        public IActionResult SaveOrganization(OrganizationModel model)
        {
            DAL_Organization organizationDal = new DAL_Organization();
            int result = 0;
            string resultMsg = "success";
            if (string.IsNullOrWhiteSpace(model.Id))
            {
                if (!organizationDal.IsExists(did:model.Did,rid:model.Rid,name:model.Name))
                {
                    result = organizationDal.InsertOrganization(model);
                }
                else
                    resultMsg = $"该部门的角色下已存在名称为 {model.Name} 的组织";
            }
            else
            {
                if(organizationDal.IsExists(id:model.Id,isRepeat:false))
                {
                    if(!organizationDal.IsExists(model.Id,model.Did,model.Rid,model.Name,true))
                        result = organizationDal.EditOrganization(model);
                    else
                        resultMsg = $"该部门的角色下已存在名称为 {model.Name} 的组织";
                }
                else
                    resultMsg = $"该组织不存在或已删除";

            }
            return new JsonResult(new
            {
                code = result > 0 ? 0 : 1,
                msg = resultMsg
            });

        }

        /// <summary>
        /// 组织详情信息
        /// </summary>
        [HttpGet("detail")]
        public IActionResult Detial(string id)
        {
            OrganizationModel organization = new OrganizationModel();
            DAL_Organization organizationDal = new DAL_Organization();
            organization = organizationDal.GetOrganizationDetail(id);
            return new JsonResult(new { code = 0, msg = "success", data = organization });
        }



        /// <summary>
        /// 删除组织信息
        /// </summary>
        [HttpPost("deleteorganization")]
        public IActionResult DeleteOrganization(string id)
        {
            DAL_Organization organizationDal = new DAL_Organization();
            int resultCode = 0;
            string resultMsg = "删除成功";
            if (organizationDal.IsExists(id))
                resultCode = organizationDal.DeleteOrganization(id);
            else
                resultMsg = "该组织不存在或已被删除";

            return new JsonResult(new
            {
                code = resultCode > 0 ? 0 : 1,
                msg = resultMsg
            });
        }

        /// <summary>
        /// 获取部门数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("getdepartments")]
        public IActionResult GetDepartments()
        {
            List<DepartmentModel> departments = new List<DepartmentModel>();
            DAL_Organization organizationDal = new DAL_Organization();
            departments = organizationDal.GetDepartments();
            return new JsonResult(new { code = 0, msg = "success", data = departments });
        }

        /// <summary>
        /// 根据部门Id获取角色数据
        /// </summary>
        /// <param name="did"></param>
        /// <returns></returns>
        [HttpGet("getroles")]
        public IActionResult GetRolesByDid(string did)
        {
            List<RoleModel> list = new List<RoleModel>();
            DAL_Organization organizationDal = new DAL_Organization();
            list= organizationDal.GetRolesByDid(did);
            return new JsonResult(new { code = 0, msg = "success", data = list });
        }

        /// <summary>
        /// 获取组织所在部门下的人员数据
        /// </summary>
        /// <param name="did">部门Id</param>
        /// <param name="oid">组织Id</param>
        /// <returns></returns>
        [HttpGet("getpersons")]
        public IActionResult GetPersons(string did,string oid)
        {
            List<PersonModel> persons = new List<PersonModel>();
            DAL_Organization organizationDal = new DAL_Organization();
            persons = organizationDal.GetPersons(did,oid);
            //组织人员Id数据
            var checkedIds = organizationDal.GetPersonIds(oid)?.ToArray();
            return new JsonResult(new { code = 0, msg = "success", data = persons , checkedIds = checkedIds, });
        }

        /// <summary>
        /// 保存组织下人员数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("saveorganizationperson")]
        public IActionResult SaveOrganizationPerson([FromBody] OrganizationPersonSaveModel model)
        {
            DAL_Organization organizationDal = new DAL_Organization();
            //清除当前组织下人员的组织、角色信息
            organizationDal.ClearPersonInfo(model.Oid);
            foreach (var item in model.Pids)
            {
                organizationDal.EditPersonInfo(item,model.Oid,model.Rid);
            }
            //组织人员Id数据
            var checkedIds = organizationDal.GetPersonIds(model.Oid)?.ToArray();
            return new JsonResult(new
            {
                code = 0,
                msg = "success",
                data = checkedIds
            });
        }

    }
}
